﻿#include "UploadFileResponse1Private.h"
#include "qftp.h"
#include "UploadFileResponse1.h"

BEGIN_NAMESPACE_ZFTPNS

UploadFileResponse1Private::UploadFileResponse1Private(QObject *parent) :
    ZFtpResponsePrivate(parent),
    q_ptr(NULL)
{

}

void UploadFileResponse1Private::listenTo(QSharedPointer<QFtp> ftp, QSharedPointer<ZFtpConfig> cfg)
{
    ZFtpResponsePrivate::listenTo(ftp, cfg);

    if (!ftp) return;

    m_current_ftp = ftp;

    ftp->disconnect(this, SLOT(slotCommandFinished(int,bool)));
    ftp->disconnect(this, SLOT(slotUploadFileProgress(qint64,qint64)));
    ftp->disconnect(this, SLOT(slotFtpStateChanged(int)));

    connect(ftp.data(), SIGNAL(commandFinished(int,bool)), SLOT(slotCommandFinished(int,bool)));
    connect(ftp.data(), SIGNAL(dataTransferProgress(qint64,qint64)), SLOT(slotUploadFileProgress(qint64,qint64)));
    connect(ftp.data(), SIGNAL(stateChanged(int)), SLOT(slotFtpStateChanged(int)));
}

void UploadFileResponse1Private::setPublicResponseObject(QPointer<ZFtpResponse> response)
{
    ZFtpResponsePrivate::setPublicResponseObject(response);
    q_ptr = qobject_cast<UploadFileResponse1 *>(response.data());
    Q_ASSERT(q_ptr);
}

QPointer<ZFtpResponse> UploadFileResponse1Private::publicObject()
{
    return QPointer<ZFtpResponse>(q_ptr);
}

void UploadFileResponse1Private::slotUploadFileProgress(qint64 done, qint64 total)
{
    // 传输进度信号为上传和下载公用的信号，需要进行过滤
    Q_ASSERT(m_current_ftp);
    if (m_current_ftp->currentId() != this->ftpTaskID())
        return;

    emit q_ptr->sigUploadProgress(done, total);
}

void UploadFileResponse1Private::slotCommandFinished(int id, bool error)
{
    if (id != ftpTaskID()) return;
    invalidFtpTaskID();

    Q_ASSERT(q_ptr);

#if 0
    emit q_ptr->sigResult(!error);
#else
    // 异步非阻塞消息
    QMetaObject::invokeMethod(q_ptr, "sigResult", Qt::QueuedConnection, Q_ARG(bool, !error));
#endif
}

void UploadFileResponse1Private::slotFtpStateChanged(int state)
{
}

END_NAMESPACE
